package com.jlcindia.util;

import java.io.Serializable;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

public class JPATemplate {
	
	public static void save(Object obj){
		try{
			EntityManagerFactory factory = JPAUtil.getEntityManagerFactory();
			EntityManager manager = factory.createEntityManager();
			EntityTransaction tx = manager.getTransaction();
			tx.begin();
			manager.persist(obj);
			tx.commit();
			manager.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void update(Object obj){
		try{
			EntityManagerFactory factory = JPAUtil.getEntityManagerFactory();
			EntityManager manager = factory.createEntityManager();
			EntityTransaction tx = manager.getTransaction();
			tx.begin();
			manager.merge(obj);
			tx.commit();
			manager.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void delete(Class cls,int cid){
		try{
			EntityManagerFactory factory = JPAUtil.getEntityManagerFactory();
			EntityManager manager = factory.createEntityManager();
			EntityTransaction tx = manager.getTransaction();
			tx.begin();
			Object obj = manager.find(cls, cid);
			manager.remove(obj);
			tx.commit();
			manager.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static Object load(Class cls,int cid){
		Object obj = null;
		try{
			EntityManagerFactory factory = JPAUtil.getEntityManagerFactory();
			EntityManager manager = factory.createEntityManager();
			EntityTransaction tx = manager.getTransaction();
			tx.begin();
			obj = manager.find(cls, cid);
			tx.commit();
			manager.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return obj;
	}

}
